package com.willpower.eureka.auth;

import com.willpower.eureka.auth.exception.ValidateCodeException;
import com.willpower.eureka.auth.response.Result;
import com.willpower.eureka.auth.response.ResultCode;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: wen-yi;
 * @date: 2021/11/2 22:32;
 * @Description:
 */
@Component("myAuthenticationFailureHandler")
public class MyAuthenticationFailureHandler extends JSONAuthentication implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        Result result = null;
        if (e instanceof AccountExpiredException){
            result = Result.fail(ResultCode.USER_ACCOUNT_EXPIRED);
        } else if (e instanceof BadCredentialsException){
            result = Result.fail(ResultCode.USER_CREDENTIALS_ERROR);
        } else if (e instanceof CredentialsExpiredException){
            result = Result.fail(ResultCode.USER_CREDENTIALS_EXPIRED);
        } else if (e instanceof DisabledException){
            result = Result.fail(ResultCode.USER_ACCOUNT_DISABLE);
        } else if (e instanceof LockedException){
            result = Result.fail(ResultCode.USER_ACCOUNT_LOCKED);
        } else if(e instanceof InternalAuthenticationServiceException){
            result = Result.fail(ResultCode.USER_ACCOUNT_NOT_EXIST);
        } else if(e instanceof ValidateCodeException){
            result = Result.fail(ResultCode.USER_VERIFY_CODE_EXPIRED);
        }
        else {
            result = Result.fail();
        }
        //处理编码问题，防止中文乱码
        //response.setContentType("text/json;charset=utf-8");
        //response.getWriter().write(new ObjectMapper().writeValueAsString(result));
        this.WriteJSON(request, response, result);
    }
}
